package repository;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.ibatis.session.SqlSession;

import util.HuishiUtil;

import model.BalanceHistoryDO;
import model.TradeDO;

import com.iwallet.biz.common.util.money.Money;

import dao.BalanceHistoryDAO;
import dao.TradeDAO;

public class IBatisTradeRepositoryImpl implements TradeRepository {
	private SqlSession session = null;
	
	@Override
	public int createTrade(String sellerAccNo, String buyerAccNo,
			Money amount, String commodity, String tradeType) {
		try{
			session = HuishiUtil.openSession("dao/sql-map-config.xml");
			TradeDAO trade = new TradeDAO();
			trade.setAmount((int)amount.getCent());
			trade.setBuyerAccNo(buyerAccNo);
			trade.setCommodity(commodity);
			trade.setSellerAccNo(sellerAccNo);
			trade.setType(tradeType);
			
			session.insert("createTrade", trade);
			session.commit();
			return trade.getTradeNo();
		}	finally{
			HuishiUtil.closeSession(session);
		}
	}

	@Override
	public List<TradeDO> queryAccountTrade(String accountNo, Date startDate,
			Date endDate, String status, String tradeType) {
		try{
			session = HuishiUtil.openSession("dao/sql-map-config.xml");
			TradeDAO trade = new TradeDAO();
			trade.setGmtCreate(startDate);
			trade.setSellerAccNo(accountNo);
			trade.setGmtModified(endDate);
			trade.setStatus(status);
			trade.setType(tradeType);
			
			List<TradeDAO> tDAOList = session.selectList("queryAccountTrade",trade);
			return convertTradeDAO2DO(tDAOList);
		}	finally{
			HuishiUtil.closeSession(session);
		}
	}

	private List<TradeDO> convertTradeDAO2DO(List<TradeDAO> tDAOList){
		List<TradeDO> resultList = new ArrayList<TradeDO>();
		for(TradeDAO tDAO:tDAOList){
			TradeDO tDO = new TradeDO();
			tDO.setBuyerAccNo(tDAO.getBuyerAccNo());
			tDO.setSellerAccNo(tDAO.getSellerAccNo());
			int balance = tDAO.getAmount();
			tDO.setAmount(new Money(balance/100,balance));
			tDO.setGmtCreate(tDAO.getGmtCreate());
			tDO.setTradeNo(tDAO.getTradeNo());
			tDO.setCommodity(tDAO.getCommodity());
			tDO.setGmtModified(tDAO.getGmtModified());
			tDO.setStatus(tDAO.getStatus());
			tDO.setType(tDAO.getType());
			
			resultList.add(tDO);
		}
		
		return resultList;
	}
}
